// 全局变量
let currentTime = 12;
let currentAngle = 45;
let currentIntensity = 75;
let currentWeather = 'sunny';

// DOM 元素
const timeSlider = document.getElementById('time-slider');
const angleSlider = document.getElementById('angle-slider');
const intensitySlider = document.getElementById('intensity-slider');
const weatherSelect = document.getElementById('weather-select');

const timeValue = document.getElementById('time-value');
const angleValue = document.getElementById('angle-value');
const intensityValue = document.getElementById('intensity-value');

const sunPosition = document.getElementById('sun-position');
const solarPanel = document.getElementById('solar-panel');
const lightRays = document.getElementById('light-rays');
const efficiencyValue = document.getElementById('efficiency-value');

const currentPower = document.getElementById('current-power');
const dailyEnergy = document.getElementById('daily-energy');
const savings = document.getElementById('savings');

// 初始化
document.addEventListener('DOMContentLoaded', function() {
    initializeSimulator();
    setupEventListeners();
    updateDisplay();
});

// 初始化模拟器
function initializeSimulator() {
    updateSunPosition();
    updateSolarPanel();
    updateLightRays();
    updateMetrics();
}

// 设置事件监听器
function setupEventListeners() {
    timeSlider.addEventListener('input', handleTimeChange);
    angleSlider.addEventListener('input', handleAngleChange);
    intensitySlider.addEventListener('input', handleIntensityChange);
    weatherSelect.addEventListener('change', handleWeatherChange);

    // 导航栏滚动效果
    window.addEventListener('scroll', handleScroll);
    
    // 移动端菜单切换
    const navToggle = document.querySelector('.nav-toggle');
    const navMenu = document.querySelector('.nav-menu');
    
    if (navToggle) {
        navToggle.addEventListener('click', function() {
            navMenu.classList.toggle('active');
        });
    }
}

// 处理时间变化
function handleTimeChange(e) {
    currentTime = parseFloat(e.target.value);
    timeValue.textContent = formatTime(currentTime);
    updateDisplay();
}

// 处理角度变化
function handleAngleChange(e) {
    currentAngle = parseInt(e.target.value);
    angleValue.textContent = currentAngle + '°';
    updateDisplay();
}

// 处理强度变化
function handleIntensityChange(e) {
    currentIntensity = parseInt(e.target.value);
    intensityValue.textContent = currentIntensity + '%';
    updateDisplay();
}

// 处理天气变化
function handleWeatherChange(e) {
    currentWeather = e.target.value;
    updateDisplay();
}

// 格式化时间
function formatTime(hours) {
    const h = Math.floor(hours);
    const m = Math.round((hours - h) * 60);
    return `${h.toString().padStart(2, '0')}:${m.toString().padStart(2, '0')}`;
}

// 更新显示
function updateDisplay() {
    updateSunPosition();
    updateSolarPanel();
    updateLightRays();
    updateEfficiency();
    updateMetrics();
    updateBackground();
}

// 更新太阳位置
function updateSunPosition() {
    const canvas = document.querySelector('.simulation-canvas');
    const canvasRect = canvas.getBoundingClientRect();
    
    // 根据时间和角度计算太阳位置
    const timeProgress = currentTime / 24;
    const x = canvasRect.width * timeProgress;
    const y = canvasRect.height * (0.3 - (currentAngle / 90) * 0.25);
    
    sunPosition.style.left = `${x - 25}px`;
    sunPosition.style.top = `${y}px`;
    
    // 根据天气调整太阳亮度
    let opacity = 1;
    switch(currentWeather) {
        case 'cloudy':
            opacity = 0.7;
            break;
        case 'overcast':
            opacity = 0.4;
            break;
        default:
            opacity = 1;
    }
    
    sunPosition.style.opacity = opacity;
}

// 更新太阳能板
function updateSolarPanel() {
    // 根据太阳角度调整太阳能板倾斜角度
    const panelAngle = Math.min(currentAngle, 60);
    solarPanel.style.transform = `translateX(-50%) rotateX(${panelAngle}deg)`;
}

// 更新光线效果
function updateLightRays() {
    const canvas = document.querySelector('.simulation-canvas');
    const canvasRect = canvas.getBoundingClientRect();
    
    // 清除现有光线
    lightRays.innerHTML = '';
    
    // 计算光线数量和强度
    const rayCount = Math.floor(currentIntensity / 10);
    const rayOpacity = currentIntensity / 100 * 0.5;
    
    // 创建光线
    for (let i = 0; i < rayCount; i++) {
        const ray = document.createElement('div');
        ray.style.position = 'absolute';
        ray.style.width = '2px';
        ray.style.background = `linear-gradient(to bottom, rgba(255, 235, 59, ${rayOpacity}), transparent)`;
        ray.style.transformOrigin = 'top';
        
        // 随机光线位置
        const startX = Math.random() * canvasRect.width;
        const endX = startX + (Math.random() - 0.5) * 50;
        
        ray.style.left = `${startX}px`;
        ray.style.top = '0';
        ray.style.height = `${canvasRect.height}px`;
        ray.style.transform = `rotate(${Math.atan2(canvasRect.height, endX - startX) * 180 / Math.PI}deg)`;
        
        lightRays.appendChild(ray);
    }
}

// 更新效率显示
function updateEfficiency() {
    // 计算效率（基于时间、角度、强度和天气）
    let efficiency = 0;
    
    // 时间因子（白天效率更高）
    const timeFactor = (currentTime >= 6 && currentTime <= 18) ? 
        Math.sin((currentTime - 6) / 12 * Math.PI) : 0;
    
    // 角度因子（最佳角度为45度）
    const angleFactor = Math.cos(Math.abs(currentAngle - 45) * Math.PI / 180);
    
    // 强度因子
    const intensityFactor = currentIntensity / 100;
    
    // 天气因子
    let weatherFactor = 1;
    switch(currentWeather) {
        case 'cloudy':
            weatherFactor = 0.7;
            break;
        case 'overcast':
            weatherFactor = 0.3;
            break;
    }
    
    // 综合效率计算
    efficiency = Math.round(timeFactor * angleFactor * intensityFactor * weatherFactor * 100);
    efficiency = Math.max(0, Math.min(100, efficiency));
    
    efficiencyValue.textContent = efficiency + '%';
    
    // 更新效率圆环颜色
    const circle = document.querySelector('.efficiency-circle');
    if (efficiency > 80) {
        circle.style.color = 'var(--success-color)';
    } else if (efficiency > 50) {
        circle.style.color = 'var(--warning-color)';
    } else {
        circle.style.color = 'var(--accent-color)';
    }
}

// 更新指标
function updateMetrics() {
    // 基于当前条件计算功率
    const basePower = 5; // 基础功率 5kW
    const efficiency = parseInt(efficiencyValue.textContent) / 100;
    const power = (basePower * efficiency).toFixed(1);
    
    // 计算日发电量（简化计算）
    const dailyHours = 8; // 假设平均日照8小时
    const dailyKWh = (power * dailyHours).toFixed(1);
    
    // 计算节省费用（假设每度电0.6元）
    const savingsAmount = (dailyKWh * 0.6).toFixed(1);
    
    // 更新显示
    currentPower.textContent = power + ' kW';
    dailyEnergy.textContent = dailyKWh + ' kWh';
    savings.textContent = '¥' + savingsAmount;
}

// 更新背景
function updateBackground() {
    const canvas = document.querySelector('.sky-background');
    
    // 根据时间和天气更新天空颜色
    let skyColor1, skyColor2;
    
    if (currentTime >= 6 && currentTime < 12) {
        // 早晨
        skyColor1 = '#87CEEB';
        skyColor2 = '#98FB98';
    } else if (currentTime >= 12 && currentTime < 18) {
        // 下午
        skyColor1 = '#4682B4';
        skyColor2 = '#90EE90';
    } else if (currentTime >= 18 && currentTime < 20) {
        // 傍晚
        skyColor1 = '#FF6347';
        skyColor2 = '#FFD700';
    } else {
        // 夜晚
        skyColor1 = '#191970';
        skyColor2 = '#000080';
    }
    
    // 天气影响
    if (currentWeather === 'cloudy') {
        skyColor1 = '#708090';
        skyColor2 = '#696969';
    } else if (currentWeather === 'overcast') {
        skyColor1 = '#2F4F4F';
        skyColor2 = '#696969';
    }
    
    canvas.style.background = `linear-gradient(to bottom, ${skyColor1}, ${skyColor2})`;
}

// 处理滚动效果
function handleScroll() {
    const navbar = document.querySelector('.navbar');
    if (window.scrollY > 100) {
        navbar.style.background = 'rgba(10, 14, 23, 0.95)';
    } else {
        navbar.style.background = 'rgba(10, 14, 23, 0.9)';
    }
}

// 平滑滚动到模拟器
function scrollToSimulator() {
    const simulator = document.getElementById('simulator');
    simulator.scrollIntoView({ behavior: 'smooth' });
}

// 添加滚动动画
function addScrollAnimations() {
    const observerOptions = {
        threshold: 0.1,
        rootMargin: '0px 0px -50px 0px'
    };

    const observer = new IntersectionObserver((entries) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                entry.target.classList.add('animate-in');
            }
        });
    }, observerOptions);

    // 观察所有需要动画的元素
    const animatedElements = document.querySelectorAll('.feature-card, .metric-card, .stat');
    animatedElements.forEach(el => observer.observe(el));
}

// 初始化滚动动画
document.addEventListener('DOMContentLoaded', addScrollAnimations);

// 添加触摸支持（移动端）
if ('ontouchstart' in window) {
    let touchStartX = 0;
    let touchStartY = 0;

    document.addEventListener('touchstart', (e) => {
        touchStartX = e.touches[0].clientX;
        touchStartY = e.touches[0].clientY;
    });

    document.addEventListener('touchmove', (e) => {
        if (!e.target.classList.contains('slider')) {
            e.preventDefault();
        }
    });
}

// 性能优化：节流函数
function throttle(func, limit) {
    let inThrottle;
    return function() {
        const args = arguments;
        const context = this;
        if (!inThrottle) {
            func.apply(context, args);
            inThrottle = true;
            setTimeout(() => inThrottle = false, limit);
        }
    };
}

// 使用节流优化滚动事件
window.addEventListener('scroll', throttle(handleScroll, 100));

// 键盘快捷键
document.addEventListener('keydown', (e) => {
    if (e.key === 'ArrowLeft' && e.ctrlKey) {
        e.preventDefault();
        timeSlider.value = Math.max(0, currentTime - 0.5);
        handleTimeChange({ target: timeSlider });
    } else if (e.key === 'ArrowRight' && e.ctrlKey) {
        e.preventDefault();
        timeSlider.value = Math.min(24, currentTime + 0.5);
        handleTimeChange({ target: timeSlider });
    }
});

// 自动演示模式
let demoMode = false;
let demoInterval;

function startDemo() {
    if (demoMode) return;
    
    demoMode = true;
    let demoTime = 6;
    
    demoInterval = setInterval(() => {
        demoTime += 0.1;
        if (demoTime > 18) demoTime = 6;
        
        timeSlider.value = demoTime;
        handleTimeChange({ target: timeSlider });
    }, 200);
}

function stopDemo() {
    if (!demoMode) return;
    
    demoMode = false;
    clearInterval(demoInterval);
}

// 添加演示按钮（可选）
document.addEventListener('DOMContentLoaded', () => {
    const demoButton = document.createElement('button');
    demoButton.textContent = '自动演示';
    demoButton.className = 'demo-button';
    demoButton.style.cssText = `
        position: fixed;
        bottom: 20px;
        right: 20px;
        background: var(--primary-color);
        color: white;
        border: none;
        padding: 10px 20px;
        border-radius: 20px;
        cursor: pointer;
        z-index: 1000;
    `;
    
    demoButton.addEventListener('click', () => {
        if (demoMode) {
            stopDemo();
            demoButton.textContent = '自动演示';
        } else {
            startDemo();
            demoButton.textContent = '停止演示';
        }
    });
    
    document.body.appendChild(demoButton);
});